package com.ala4.oxcafe.boot;

import com.ala4.oxcafe.boot.annotation.Permission;
import com.ala4.oxcafe.common.utils.object.ObjectUtil;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.condition.PathPatternsRequestCondition;
import org.springframework.web.servlet.mvc.condition.PatternsRequestCondition;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Pattern;

/**
 * @author PING
 * @date 2025/8/15 21:08
 */
@Data
@Configuration
public class PermitAllUrlProperties implements InitializingBean, ApplicationContextAware {

    private static final Pattern PATTERN = Pattern.compile("\\{(.*?)\\}");
    public final String ASTERISK = "*";
    private ApplicationContext applicationContext;
    private List<String> urls = new ArrayList<>();

    public static String replaceAll(final String text, final Pattern regex, final String replacement) {
        if (ObjectUtil.anyNull(text, regex, replacement)) {
            return text;
        }
        return regex.matcher(text).replaceAll(replacement);
    }

    @Override
    public void afterPropertiesSet() {
        RequestMappingHandlerMapping mapping = applicationContext.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> map = mapping.getHandlerMethods();

        map.keySet().forEach(info -> {
            HandlerMethod handlerMethod = map.get(info);

            // 获取方法上边的注解 替代path variable 为 *
            Permission method = AnnotationUtils.findAnnotation(handlerMethod.getMethod(), Permission.class);
            Optional.ofNullable(method).ifPresent(permission -> {
                // 公开权限才去添加
                if (permission.permissionPublic()) {
                    // 两种风格的URL？
                    PathPatternsRequestCondition pathPatternsCondition = info.getPathPatternsCondition();
                    Optional.ofNullable(pathPatternsCondition).ifPresent(pathPatterns ->
                            pathPatterns.getPatterns().forEach(pattern -> urls.add(pattern.getPatternString())));

                    PatternsRequestCondition patternsCondition = info.getPatternsCondition();
                    Optional.ofNullable(patternsCondition).ifPresent(patterns -> urls.addAll(patterns.getPatterns()));
                }
            });

//            // 获取类上边的注解, 替代path variable 为 *
//            Permission controller = AnnotationUtils.findAnnotation(handlerMethod.getBeanType(), Permission.class);
//            Optional.ofNullable(controller).ifPresent(apiPermission -> Objects.requireNonNull(info.getPatternsCondition().getPatterns())
//                    .forEach(url -> urls.add(replaceAll(url, PATTERN, ASTERISK))));
        });
    }

    @Override
    public void setApplicationContext(ApplicationContext context) throws BeansException {
        this.applicationContext = context;
    }
}
